package org.dim.oa.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.dim.oa.po.ServerResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Spring security登录成功处理类,返回jwt====token在此处颁发
 *  * GYB
 *  * 20190220
 */
@Component
public class AuthenSuccessGeneTokenHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        System.out.println("登录成功");
        System.out.println("全局获取到的用户信息为："+ SessionUser.getCurUser().toString());
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("UTF-8");
        //从authentication中获取用户信息
        final SessionUser userDetail = (SessionUser) authentication.getPrincipal();
        ServerResponse<SessionUser> success = ServerResponse.success(userDetail);
        ObjectMapper objectMapper = new ObjectMapper();
        String res = objectMapper.writeValueAsString(success);
        httpServletResponse.getWriter().write(res);
        httpServletResponse.getWriter().flush();
    }
}